#! /usr/bin/env python

import roslib; roslib.load_manifest('storage')
import rospy
import sqlite3
import actionlib
import std_msgs
import os
from storage.msg import *

pub = rospy.Publisher("android_request",android)
databaseString = '/u/cse553/ros/robotic-photographer-read-only/storage/storageDB'

def addPerson(target):
	conn4 = sqlite3.connect(databaseString)
	c4 = conn4.cursor()
	if target[0]=="get":
		if target[1]=="mainBio":
			c4.execute('select * from mainBio')
		elif target[1]=="peopleDictionary":
			c4.execute('select * from peopleDictionary')
		result=addPersonResult()
		for row in c4:
			result.result.append(str(row))
		conn4.commit()
		c4.close()
		return result
	elif target[0]=="set":
		ins=[]
		for i in range(len(target)-2):
			ins.append(target[2+i])
		if target[1]=="mainBio":
			c4.execute('insert into mainBio values(NULL,?,?,?,?,?,?,?,?,?)',ins)
		elif target[1]=="peopleDictionary":
			c4.execute('insert into peopleDictionary values(NULL,?,?,?,?,?,?,?,?)',ins)
		result=addPersonResult()
		conn4.commit()
		c4.close()
		return result
def addImage(target):
	conn2 = sqlite3.connect(databaseString)
	c2 = conn2.cursor()
	img=(target[0],target[1],target[2])
	c2.execute('insert into images values (?,?,?)', img)
	imageID=target[0]
	conn2.commit()
	c2.close()
	path=target[2]  
	dirList=os.listdir(path)
	#will place the 'path' variable instead of "data" once we are running from the same place
	mesg=["storageUser",str(imageID),"data"]
	for fname in dirList:
		rospy.loginfo(os.stat(path+"/"+fname).st_size)
		if os.stat(path+"/"+fname).st_size>40000:
			os.remove(path+"/"+fname)
	pub.publish(android(6,mesg))
	rospy.loginfo("this happened")

def updateEyeDist(record):
	rospy.loginfo("updating eyedist")
	conn3 = sqlite3.connect(databaseString)
	c3 = conn3.cursor()
	rospy.loginfo("start")
	for string in record:
		rospy.loginfo(string)
	eyeDist=float(record[2])
	width=float(record[5])
	ratio=round(eyeDist/width,4)
	entry=record
	entry.insert(7,str(ratio))
	for string in entry:
		rospy.loginfo(string)
	c3.execute('insert into androidBio values (NULL,?,NULL,?,?,?,?,?,?,?,?)',entry)
	rospy.loginfo("end")
	conn3.commit()
	c3.close() 

class storageServer:
  def __init__(self):
    self.server = actionlib.SimpleActionServer("addImage", addImageAction, self.execute, False)
    self.server.start()

  def execute(self,goal):
    addImage(goal.target)
    #once we have reached our target we tell the client that we succeeded
    self.server.set_succeeded()

class storageServer:
  def __init__(self):
    self.server = actionlib.SimpleActionServer("addPerson", addPersonAction, self.execute, False)
    self.server.start()

  def execute(self,goal):
    result=addPerson(goal.target)
    #once we have reached our target we tell the client that we succeeded
    self.server.set_succeeded(result)
    
class eyeDistServer:
  def __init__(self):
	  self.eyeServer = actionlib.SimpleActionServer("storage_msg", storage_msgAction, self.execute, False)
	  self.eyeServer.start()
	  
  def execute(self,goal):
	  updateEyeDist(goal.record)
	  #rospy.loginfo(goal.record[0])
	  self.eyeServer.set_succeeded()

if __name__ == '__main__':
	#NOTE: Gotta Make the node executable : chmod +x nodes/storageServer.py
	rospy.init_node("storageServer")
	
	conn = sqlite3.connect(databaseString)
	c = conn.cursor()

	# Create table
	c.execute("""create table if not exists androidBio(faceID integer primary key autoincrement, imageID integer,personID int,confidence real, eyeDistance real, midX real, midY real,imgWidth int, imgHeight int,eyeDistRatio real, URL string)""")
	c.execute("""create table if not exists peopleDictionary(personID integer primary key autoincrement, name string, eyeDistance real, midX real, midY real, height real,faceR real, faceG real, faceB real, shirtR real, shirtG real, shirtB real )""")
	c.execute("""create table if not exists mainBio(bioID integer primary key autoincrement, imageID integer,personID int, height real,faceR real, faceG real, faceB real, shirtR real, shirtG real, shirtB real)""")
	c.execute("""create table if not exists images(imageID integer primary key, url string, facesPath string)""")
	# Save (commit) the changes
	conn.commit()
	c.close()
	eyeServer=eyeDistServer()
	server=storageServer()
	rospy.spin()
